#include "util.h"
#include "string.h"

void DecodeUUI(std::string src, std::string& dest)
{
	dest = src;

	try
	{
		// head:4byte + len:2byte
		if (src.length() >= 6 && (src.substr(0, 4) == "00C8" || src.substr(0, 4) == "00c8"))
		{
			std::string slen = src.substr(4, 2);
			int len = (util::char2int(slen[0]) * 16 + util::char2int(slen[1])) * 2;		// 4-6位是长度，表示uui有多少个字符，这�??2�??16进制描述一个char编码后需�??*2
			std::string sRes = src.substr(6, len);

			dest = util::hex2str(sRes);
		}
	}
	catch (...) {}
}

void EncodeUUI(std::string src, std::string& dest)
{
	if (src.length() > 256 || src.length() <= 0)
	{
		dest = "";
		return;
	}
	std::string hex = util::str2hex(src);
	char buffer[1024];
	sprintf(buffer, "00C8%02X%s", int(src.length()), hex.c_str());
	dest = buffer;
}

extern "C" int uui_decode(const char* in, char* out)
{
    if(!in || !out)
        return -1;

    std::string strOut;
    DecodeUUI(in, strOut);

    strcpy(out, strOut.c_str());
    return 0;
}

extern "C" int uui_encode(const char* in, char* out)
{
    
    if(!in || !out)
        return -1;

    std::string strOut;
    EncodeUUI(in, strOut);

    strcpy(out, strOut.c_str());
    return 0;
}